package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocketServer.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单接口实现类相关接口
 */
@Service
//加上事务注解避免插入订单时，订单与订单详细数据不一致
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    public OrderSubmitVO insertOrder(OrdersSubmitDTO ordersSubmitDTO) {
//        1.处理异常情况(地址为空，不能提交订单;购物车的商品为空，也不能提交订单)
        Long addressId = ordersSubmitDTO.getAddressBookId();
        AddressBook address = addressBookMapper.getById(addressId);
        if (address == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> Cart = shoppingCartMapper.getById(shoppingCart);

        if (Cart == null || Cart.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
//        2.往订单表插入订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(address.getPhone());
        orders.setAddress(address.getDetail());
        orders.setConsignee(address.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);

        orderMapper.insertBatch(orders);
//        3.往订单详细表批量插入订单下的订单商品信息
        List<OrderDetail> OrderDetailList = new ArrayList<>();
        for (ShoppingCart cart : Cart) {
            OrderDetail orderDetail = new OrderDetail(); //订单明细对象
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(cart, orderDetail);
            OrderDetailList.add(orderDetail);
        }
        orderMapper.insertOD(OrderDetailList);

//      4.清空购物车
        shoppingCartMapper.Clean(userId);

//      5.封装订单提交Vo对象
        OrderSubmitVO orderSubmitVo = OrderSubmitVO.builder().
                orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .id(orders.getId())
                .build();

        return orderSubmitVo;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
        //没有商户就就跳过支付（前端：重定向到支付成功），直接更新状态（后端直接调用paySuccess来实现状态的更新）
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();//这里返回一个orderPaymentVo对象即可
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
//        通过websocket响应客户端发送消息
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }


    /**
     * 历史订单分页查询
     * @param
     * @return
     */
    @Override
    public PageResult pageQuery(int page, int pageSize, Integer status) {
        /**
         * 这个startPage最好放在第一行先执行，
         * 这样才能分页加上limit，
         * 不然相当于没用到pageHelper，返回total变为0
         */
        PageHelper.startPage(page, pageSize);
        //      分页查询订单基本信息
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> PageOrders=orderMapper.page(ordersPageQueryDTO);

       List<OrderVO> record = new ArrayList();

        if(PageOrders !=null && PageOrders.size()>0){
            for (Orders pageOrder : PageOrders) {
//        获得订单id
                Long orderId = pageOrder.getId();
                OrderVO orderVO = new OrderVO();
 //       查询订单详情
                List<OrderDetail> DetailList =orderDetailMapper.listByOrderId(orderId);
                BeanUtils.copyProperties(pageOrder,orderVO);
                orderVO.setOrderDetailList(DetailList);
                record.add(orderVO);
            }

        }
        //          最后封装订单信息
        long total = PageOrders.getTotal();
        return  new PageResult(total,record);
    }

    /**
     * 根据订单id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
//      1.先查询一条订单信息
        Orders orders=orderMapper.getOrderById(id);
//      2.根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        OrderVO orderVO = new OrderVO();
        if(orderDetails !=null && orderDetails.size()>0){
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetails);
        }
//      3.封装Vo对象
        return orderVO;
    }

    /**
     * 根据订单id修改订单的取消状态
     * @param id
     */
    public void cancelOrderById(Long id) throws Exception {
        Orders order = orderMapper.getOrderById(id);
        Orders orders = new Orders();
        orders.setId(order.getId());
//        1.如果订单不存在,则抛出一个订单不存在异常
      if(order ==null){
          throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
      }
//      2.如果订单不是待付款和待接单状态下，则抛出状态出错异常给前端
      if(order.getStatus()>2){
          throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
      }
//      3.如果在待接单状态下取消订单，需要给用户退款
        if(order.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(order.getCancelReason());
//        4.根据订单id修改订单
        orderMapper.update(orders);
    }

    /**
     * 再来一单接口
     * @param id
     */
    public void againOrder(Long id) {
//        要求:将订单的商品重新添加到购物车上
//        1.查询该订单下的所有餐品
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
//        2.将餐品添加到购物车上
        Long userId = BaseContext.getCurrentId();
        if(orderDetails !=null && orderDetails.size()>0){
            List<ShoppingCart> CartList = new ArrayList();
            for (OrderDetail orderDetail : orderDetails) {
                ShoppingCart Cart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail,Cart);
                Cart.setCreateTime(LocalDateTime.now());
                Cart.setUserId(userId);
                CartList.add(Cart);
            }
            /**
             * 批量插入购物车餐品
             */
            shoppingCartMapper.insertCartList(CartList);
        }
    }
    /**
     * 订单搜索
     * @param oPqDTO
     * @return
     */
    public PageResult AdminPageQuery(OrdersPageQueryDTO oPqDTO) {
        PageHelper.startPage(oPqDTO.getPage(),oPqDTO.getPageSize());
        //      分页查询订单基本信息
        Page<Orders> PageOrders=orderMapper.page(oPqDTO);
        List<OrderVO> record = new ArrayList();
        if(PageOrders !=null && PageOrders.size()>0){
            for (Orders pageOrder : PageOrders) {
                //        获得订单id
                Long orderId = pageOrder.getId();
                OrderVO orderVO = new OrderVO();
                //       查询订单详情
                List<OrderDetail> DetailList =orderDetailMapper.listByOrderId(orderId);
                BeanUtils.copyProperties(pageOrder,orderVO);
//                调用这个方法来获得订单菜品基本信息字符串
                String orderDishes = getOrderDishString(DetailList);
                orderVO.setOrderDishes(orderDishes);
                record.add(orderVO);
            }
        }
        //          最后封装订单信息
        long total = PageOrders.getTotal();
        return  new PageResult(total,record);
    }

    /**
     * 各个状态的的订单数量统计
     * @return
     */
    public OrderStatisticsVO countStatus() {
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
//       1. 查询待接单的统计数量
       Integer  PendingOrders =orderMapper.countOrder(Orders.TO_BE_CONFIRMED);
//       2.查询待派送的数量
        Integer TobeDelivered =orderMapper.countOrder(Orders.CONFIRMED);
//       3.查询派送中的数量
        Integer Delivering =orderMapper.countOrder(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(TobeDelivered);
        orderStatisticsVO.setToBeConfirmed(PendingOrders);
        orderStatisticsVO.setDeliveryInProgress(Delivering);
        return orderStatisticsVO;
    }

    /**
     * 根据订单id修改待接单状态为已接单
     * @param ordersDTO
     */
    public void UpdateStatus(OrdersDTO ordersDTO) {
        Orders order = Orders.builder()
                .id(ordersDTO.getId())
                .status(Orders.CONFIRMED).build();
        orderMapper.update(order);
    }


    /**
     * 拒单
     */
    public void Reject(OrdersRejectionDTO ordersRejectionDTO) throws  Exception{
        Long orderId = ordersRejectionDTO.getId();
        Orders order = orderMapper.getOrderById(orderId);
            Integer status = order.getStatus();
            /**
             * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
             */
            if(order ==null || ! status.equals(Orders.TO_BE_CONFIRMED)){
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            if(status==Orders.TO_BE_CONFIRMED){
                if(order.getPayStatus()==Orders.PAID){
                    order.setPayStatus(Orders.REFUND);
                }
                order.setStatus(Orders.CANCELLED);
                order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception{
        Orders order = orderMapper.getOrderById(ordersCancelDTO.getId());
        if (order == null || !order.getPayStatus().equals(Orders.PAID)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Integer PayStatus = order.getPayStatus();
//        商家取消订单时，如果用户已经完成了支付，需要为用户退款
        if(PayStatus.equals(Orders.PAID)){
            order.setPayStatus(Orders.REFUND);
        }
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        order.setStatus(Orders.CANCELLED);
        orderMapper.update(order);

    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) throws Exception {
        Orders order = orderMapper.getOrderById(id);
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(  order.getStatus().equals(Orders.CONFIRMED)){
            order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        }
        orderMapper.update(order);

    }


    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) throws Exception {
        Orders order = orderMapper.getOrderById(id);
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(  order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            order.setStatus(Orders.COMPLETED);
            order.setDeliveryTime(LocalDateTime.now());
        }
        orderMapper.update(order);
    }


    /**
     * 根据订单id拼接订单菜品字符串
     */
    public String getOrderDishString(List<OrderDetail> orderDishes){
        String orders ="";
        for (OrderDetail orderDish : orderDishes) {
            String dishFlavor = orderDish.getDishFlavor();
            if(dishFlavor !=null){
                orders =orders+ orderDish.getName() + "(" + dishFlavor + ")"+"*"+orderDish.getNumber()+";";
            }else{
                orders =orders+ orderDish.getName()+"*"+orderDish.getNumber()+";";
            }
        }
        return orders;
    }

    /**
     * 用户催单
     * @param id
     */
    public void reminder(Long id) {
        Orders order = orderMapper.getOrderById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        HashMap map = new HashMap();
        map.put("type",2);// 1 代表订单语音提醒  2 代表催单提醒
        map.put("orderId",id);
        map.put("content","您的催单订单号为:"+order.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
